package com.ruoyi.common.utils.hangxin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component("hangxinShaUtil")
public class ShaUtil {
    private static final String DEFAULT_ENCODING = "UTF-8";
    private static final Charset UTF8 = Charset.forName(DEFAULT_ENCODING);

    public static String sha256Hex(String signingKey, String stringToSign) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(signingKey.getBytes(UTF8), "HmacSHA256"));
            return new String(Hex.encodeHex(mac.doFinal(stringToSign.getBytes(UTF8))));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String getSignString(JSONObject jsp, String action, String timestamp, String noncestr) throws UnsupportedEncodingException {
        StringBuffer sb = new StringBuffer();
        sb.append(action + "|");
        List<String> keys = new ArrayList<String>();
        for (String key : jsp.keySet()) {
            keys.add(key);
        }
        Collections.sort(keys);
        System.out.println(keys);
        for (int i = 0; i < keys.size(); i++) {
            Object value = jsp.get(keys.get(i));
            if (null != value && value instanceof String) {
                sb.append(URLEncoder.encode(String.valueOf(value), "UTF-8").toLowerCase() + "|");
            } else {
                sb.append("|");
            }
        }
        sb.append(timestamp + "|" + noncestr);
        return sb.toString();
    }
//    public String getSignString(JSONArray jsp, String action, String timestamp, String noncestr) throws UnsupportedEncodingException {
//        StringBuffer sb = new StringBuffer();
//        sb.append(action + "|");
//        List<String> keys = new ArrayList<String>();
//        for (Object key : jsp) {
//            keys.add((String) key);
//        }
//        Collections.sort(keys);
//        System.out.println(keys);
//        for (int i = 0; i < keys.size(); i++) {
//            Object value = jsp.get(i);
//            if (null != value && value instanceof String) {
//                sb.append(URLEncoder.encode(String.valueOf(value), "UTF-8").toLowerCase() + "|");
//            } else {
//                sb.append("|");
//            }
//        }
//        sb.append(timestamp + "|" + noncestr);
//        return sb.toString();
//    }

    public static String getSignString(String taxcode, String cusname, String noncestr) throws UnsupportedEncodingException {
        return noncestr + "|" + cusname + "|" + taxcode;
    }

}
